package com.excilys.formation.project.services.impl;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.excilys.formation.project.entities.Client;
import com.excilys.formation.project.model.ClientUser;
import com.excilys.formation.project.repository.ClientDAO;

/**
 * Implémentation de {@link ClientService}.
 * 
 * @author excilys
 * 
 */
@Service("clientService")
@Transactional(readOnly = true)
public class ClientServiceImpl implements UserDetailsService {

	/**
	 * Instance du ClientDAO pour le service.
	 */
	@Autowired
	private ClientDAO clientDAO;

	@Override
	public UserDetails loadUserByUsername(final String username) {
		Client client = clientDAO.getClientByLogin(username);

		if (client != null) {

			Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(1);
			authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

			return new ClientUser(client, authorities);
		}
		return null;
	}
}
